package com.zy.mc_module.utils;

import com.zy.mc_module.mvp.bean.BaseBean;
import com.zy.mc_module.utils.retrofit.RetrofitManager;
import com.zy.mc_module.utils.retrofit.RxTransform;

import io.reactivex.Observable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created on 18/12/4
 * 上传图片
 **/
public class ImageUpload {

    /***
     * 单张图片上传
     * @param path 图片路径
     * @param type 文件所属类型
     * @param id fileParentId  : 0
     * @return
     */
    public static Observable<BaseBean> singleImg(String path, String type, String id) {
        File file = new File(path);
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
        return RetrofitManager.getInstance().getApi().uploadImg("APP", type, file.getName(), id, filePart)
                .compose(RxTransform.schedule());
    }

    /**
     * 多张图片上传
     */
    public static Observable<BaseBean> moreImg(List<String> paths, String type, String id) {
        Map<String, RequestBody> parts = new HashMap<>();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < paths.size(); i++) {
            File file = new File(paths.get(i));
            sb.append(file.getName());
            if (i != (paths.size() - 1)) {
                sb.append(",");
            }
            RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            parts.put("files\";filename=\"" + file.getName(), requestBody);
        }
        return RetrofitManager.getInstance().getApi().uploadImgs("APP", type, sb.toString(), id, parts);

    }

    /***
     * 上传视频
     */
    public static Observable<BaseBean> singleVideo(String path) {
        File file = new File(path);
        if (file.length() > 1024 * 1024 * 8) {
            BaseBean<String> baseBean = new BaseBean();
            baseBean.code = 1;
            baseBean.msg = "too large";
            return Observable.just(baseBean);
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
        return RetrofitManager.getInstance().getApi().uploadVideo("APP", "-1", file.getName(), "0", filePart);
    }
}
